<template>
    <div class="container">
        <div class="left-content">
            <el-carousel indicator-position="outside">
                <el-carousel-item v-for="item in skuList.sku" :key="item.id" style="height: 300px">
                    <img :src="item.picture" class="image uniform-size">
                </el-carousel-item>
            </el-carousel>
        </div>
        <div class="right-content">
            <el-descriptions :title="goodsinfo.name" column="1">
                <el-descriptions-item label="价格"><span style="font-size: x-large; color: red;">￥{{ goodsinfo.price
                }}</span></el-descriptions-item>
                <el-descriptions-item label="销量">{{ goodsinfo.totalSales }}</el-descriptions-item>
                <el-descriptions-item label="优惠"></el-descriptions-item>
                <el-descriptions-item label="配送地址">
                    <el-select v-model="order.addressId" class="m-2" placeholder="Select">
                        <el-option v-for="item in address" :key="item.id" :label="item.address" :value="item.id" />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item v-for="item in specOptions.options" :key="item.id" :label="item.title">
                    <el-radio-group v-model="item.value">
                        <el-radio v-for="(option, index) in item.specOptions" :label="option" :key="index">
                        </el-radio>
                    </el-radio-group>
                </el-descriptions-item>
                <el-descriptions-item label="数量">
                    <el-input-number v-model="order.num" :min="1" :max="10" />
                </el-descriptions-item>
                <el-descriptions-item>
                    <el-button type="primary" plain @click="buyNow()">立即购买</el-button>
                    <el-button type="primary" @click="addShoppingCart()">加入购物车</el-button>
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </div>
</template>
  

<script setup lang="ts">
import api from '@/api';
import store from '@/store';
import { ElNotification } from 'element-plus';
import { computed, onMounted, reactive, ref, toRef, watch } from 'vue';
import { useRoute,useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const goodsinfo = ref({
    id: route.params.id,
    name: '',
    price: 0,
    stock: '',
    totalSales: ''
})

onMounted(() => {
    getSkuBySpuId()
    getSpuById()
    getSpecOptionsBySpuId()
    getAddressByUserId()
})

const skuList = reactive({
    sku: [
        {
            id: '',
            picture: '',
            properties: '',
        }
    ]
})

function getSkuBySpuId() {
    api.shop.getSkuBySpuId(goodsinfo.value.id)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            skuList.sku = response.data.data

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}


let p: number

function getSpuById() {
    api.shop.getSpuById(goodsinfo.value.id)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            goodsinfo.value.name = response.data.data.name
            goodsinfo.value.price = response.data.data.price
            p = response.data.data.price;
            goodsinfo.value.stock = response.data.data.stock
            goodsinfo.value.totalSales = response.data.data.totalSales
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

const specOptions = ref({
    options: [
        {
            id: '',
            title: '',
            specOptions: [],
            value: ''
        }
    ]
})

function getSpecOptionsBySpuId() {
    api.shop.getSpecOptionsBySpuId(goodsinfo.value.id)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            specOptions.value.options = response.data.data
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

const formattedOptions = computed(() => {
    return specOptions.value.options.map(option => `${option.title}:${option.value}`).join(';');
});

function buyNow() {
    if (order.num && Number.isInteger(order.num) && order.num > 0) {
        api.orders.addOrder({ skuOptions: formattedOptions.value, userId: store.getters.getUserInfo.id, addressId: order.addressId, spuId: goodsinfo.value.id, num: order.num })
            .then(response => {
                // 在这里可以处理提交成功后的逻辑
                router.push({
                    name: 'orderspay',
                    params: {
                        id: response.data.data
                    }
                });
                ElNotification({
                    title: 'Success',
                    message: response.data.msg,
                    type: 'success',
                    duration: 1500
                })

            })
            .catch(error => {
                ElNotification({
                    title: 'Error',
                    message: error.data.msg,
                    type: 'error',
                    duration: 1500
                })
                // 在这里可以处理提交失败后的逻辑
            });
    } else {
        alert("数量必须为正整数")
    }
}

const address = ref([
    {
        id: '',
        address: ''
    }
])

const order = reactive({
    addressId: '',
    num: 1,
})

watch(() => order.num, (newNum) => {
    goodsinfo.value.price = newNum*p;
});

function getAddressByUserId() {
    api.address.getAddressByUserId({ userId: store.getters.getUserInfo.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            address.value = response.data.data

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}


function addShoppingCart(){
    if (order.num && Number.isInteger(order.num) && order.num > 0) {
        api.orders.addShoppingCart({ skuOptions: formattedOptions.value, userId: store.getters.getUserInfo.id, addressId: order.addressId, spuId: goodsinfo.value.id, num: order.num })
            .then(response => {
                // 在这里可以处理提交成功后的逻辑
                ElNotification({
                    title: 'Success',
                    message: response.data.msg,
                    type: 'success',
                    duration: 1500
                })

            })
            .catch(error => {
                ElNotification({
                    title: 'Error',
                    message: error.data.msg,
                    type: 'error',
                    duration: 1500
                })
                // 在这里可以处理提交失败后的逻辑
            });
    } else {
        alert("数量必须为正整数")
    }
}

</script>

<style scoped>
.container {
    display: flex;
    justify-content: center;
    padding: 20px;
    margin-top: 80px;
}

.left-content,
.right-content {
    width: 35%;
    /* 需要适当调整左右内容的宽度比例 */
    background-color: #f8f8f8;
    margin: 10px;
    padding: 20px;
}

.image {
    width: 100%;
    display: flexbox;
}

.uniform-size {
    height: 100%;
    /* 设置图片宽度 */
    object-fit: contain;
    /* 控制图片的缩放方式，可以根据需要调整，例如contain或none */
}
</style>